/**
 * 描述: 业务逻辑处理 - 用户相关接口
 * 作者: Jack Chen
 * 日期: 2020-06-20
*/


const { querySql, queryOne,formatTime } = require('../utils/index');
const md5 = require('../utils/md5');
const jwt = require('jsonwebtoken');
const boom = require('boom');
const { body, validationResult } = require('express-validator');
const { 
  CODE_ERROR,
  CODE_SUCCESS, 
  PRIVATE_KEY, 
  JWT_EXPIRED 
} = require('../utils/constant');
const { decode } = require('../utils/user-jwt');


async function innerLogin(username, password){
  let query = `select * from sys_user where password='${password}'`;
  if(username){
    query += ` and username='${username}'`;
  }
  let ret = {};
  try{
    let user = await querySql(query);
    	// console.log('用户登录===', user);
      if (!user || user.length <= 0 || user[0].delete_flag != 0) {
        ret = { 
        	code: CODE_ERROR, 
        	msg: '用户名或密码错误', 
        	data: null 
        };
      } else {
        if( user[0].status != 0){
          ret = { 
            code: CODE_ERROR, 
            msg: '您已注册成功，请联系管理员开通，电话：13760367282（微信同号）', 
            data: {status: user[0].status} 
          };
        }else{
          // 登录成功，签发一个token并返回给前端
          const token = jwt.sign(
            // payload：签发的 token 里面要包含的一些数据。
            { username },
            // 私钥
            PRIVATE_KEY,
            // 设置过期时间
            { expiresIn: JWT_EXPIRED }
          )

          let userData = {
            id: user[0].id,
            username: user[0].username,
            nickname: user[0].nickname,
            avator: user[0].avator,
            status: user[0].status,
            cardno: user[0].cardno,
            balance: user[0].balance,
            gmt_create: user[0].gmt_create,
            user_type: user[0].user_type,
          };

          ret = { 
            code: CODE_SUCCESS, 
            msg: '登录成功', 
            data: { 
              token,
              userData
            } 
          };
        }
      }
  }catch(err){
    ret = { 
      code: CODE_ERROR, 
      msg: '查询数据失败', 
      data: err 
    };
  }
  return ret;
}

// 登录
async function login(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
    next(boom.badRequest(msg));
  } else {
    let { username, password } = req.body;
    // md5加密
    password = md5(password);
    let ret = await innerLogin(username, password);
    res.json(ret);
  }
}

// 注册
async function register(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { username, password, nickname='anonymous', age=0, sex='0' } = req.body;
    try{
      password = md5(password);
      let data = await findUser(username)
  		console.log('用户注册===', data);
  		if (data) {
        if(data.delete_flag == 0){
          res.json({ 
            code: CODE_ERROR, 
            msg: '用户已存在', 
            data: null 
          })
        }else{
          const query = `update sys_user set delete_flag=0,status=1,password='${password}',nickname='${nickname}' where id='${data.id}'`;
          let result = await querySql(query)
          // console.log('用户注册===', result);
          if (!result || result.affectedRows === 0) {
            res.json({ 
              code: CODE_ERROR, 
              msg: '注册失败', 
              data: null 
            })
          } else {
            let ret = await innerLogin(username, password);
            res.json(ret);
          }
        }
  		} else {
  			const query = `insert into sys_user(username, password, nickname, status, age, sex) values('${username}', '${password}', '${nickname}', 1, '${age}', '${sex}')`;
  			let result = await querySql(query)
        // console.log('用户注册===', result);
        if (!result || result.affectedRows === 0) {
          res.json({ 
            code: CODE_ERROR, 
            msg: '注册失败', 
            data: null 
          })
        } else {
          let ret = await innerLogin(username, password);
          if( ret.data && ret.data.status != 0 ){
            // 注册成功的用户
            ret.code = CODE_SUCCESS;
          }
          res.json(ret);
        }
  		}
    }catch(err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '注册失败', 
        data: err 
      })
    }
  }
}

// 重置密码
function resetPwd(req, res, next) {
	const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { username, oldPassword, newPassword } = req.body;
    oldPassword = md5(oldPassword);
    validateUser(username, oldPassword)
    .then(data => {
      console.log('校验用户名和密码===', data);
      if (data) {
        if (newPassword) {
          newPassword = md5(newPassword);
				  const query = `update sys_user set password='${newPassword}' where username='${username}'`;
				  querySql(query)
          .then(user => {
            // console.log('密码重置===', user);
            if (!user || user.length === 0) {
              res.json({ 
                code: CODE_ERROR, 
                msg: '重置密码失败', 
                data: null 
              })
            } else {
              res.json({ 
                code: CODE_SUCCESS, 
                msg: '重置密码成功', 
                data: null
              })
            }
          })
        } else {
          res.json({ 
            code: CODE_ERROR, 
            msg: '新密码不能为空', 
            data: null 
          })
        }
      } else {
        res.json({ 
          code: CODE_ERROR, 
          msg: '用户名或旧密码错误', 
          data: null 
        })
      }
    })
   
  }
}

// 校验用户名和密码
function validateUser(username, oldPassword) {
	const query = `select id, username from sys_user where username='${username}' and password='${oldPassword}'`;
  	return queryOne(query);
}

// 通过用户名查询用户信息
function findUser(username) {
  const query = `select id, username, user_type, delete_flag from sys_user where username='${username}'`;
  return queryOne(query);
}

// 查询用户列表
async function getUserList(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
    next(boom.badRequest(msg));
  } else {

    let { pageSize, pageNo, params } = req.body;
    
    // 默认值
    pageSize = pageSize ? pageSize : 1;
    pageNo = pageNo ? pageNo : 1;

    let query = `select id,username,password,nickname,user_type,status,gmt_create,master_id,balance,age,sex from sys_user where delete_flag=0`;
    if( params){
      if( params.id > 0){
        query += ' and id=' + params.id;
      }
      if( params.username){
        query += ' and username like \'%' + params.username + '%\'';
      }
      if( params.gmt_create){
        if( params.gmt_create.length > 0 && params.gmt_create[0]){
          query += ' and gmt_create >=\'' + params.gmt_create[0] + '\'';
          if( params.gmt_create.length > 1&& params.gmt_create[1]){
            query += ' and gmt_create <=\'' + params.gmt_create[1] + '\'';
          }
        }
      }
      if( params.nickname){
        query += ' and nickname like \'%' + params.nickname + '%\'';
      }
      if( params.status >= 0){
        query += ' and status=' + params.status;
      }
      if( params.user_type >= 0){
        query += ' and user_type=' + params.user_type;
      }
      if( params.master_id >= 0){
        query += ' and master_id=' + params.master_id;
      }
    }

    try{
      let data = await querySql(query)
    	// console.log('设备列表查询===', data);
      if (!data || data.length === 0) {
        res.json({ 
        	code: CODE_SUCCESS, 
        	msg: '暂无数据', 
        	data: null 
        })
      } else {
        // 计算数据总条数
        let total = data.length; 
        // 分页条件 (跳过多少条)
        let n = (pageNo - 1) * pageSize;
        // 拼接分页的sql语句命令
        let query_3 = query + ` order by gmt_create desc limit ${n} , ${pageSize}`;
        let result_3 = await querySql(query_3);
        if (!result_3 || result_3.length === 0) {
          res.json({ 
            code: CODE_SUCCESS, 
            msg: '暂无数据', 
            data: null 
          })
        } else {
          res.json({ 
            code: CODE_SUCCESS, 
            msg: '查询数据成功', 
            data: {
              rows: result_3,
              total: total,
              pageNo: parseInt(pageNo),
              pageSize: parseInt(pageSize),
            } 
          })
        }
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '暂无数据', 
        data: err 
      })
    }
  }
}

// 验证用户是否管理员
async function validateManager(req){
  let ret_decode = decode(req);
  if( ret_decode && ret_decode.username){
    let data = await findUser(ret_decode.username);
    if(data){
      return {isManager: data.user_type==1, self_id: data.id};
    }
    return  {isManager: false, self_id: 0};
  }
  return  {isManager: false, self_id: 0};
}


// 编辑用户
async function editUser(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    
    let { id,username,password,nickname,status,gmt_create,user_type,master_id,balance,bookIds } = req.body;
    let query = `update sys_user set username='${username}'`;
    if( password){
      password = md5(password);
      query += `, password='${password}'`
    }
    if( gmt_create){
      query += `, gmt_create='${gmt_create}'`
    }
    if( nickname){
      query += `, nickname='${nickname}'`
    }
    if( status !== undefined){
      query += `, status=${status}`
    }
    if( user_type !== undefined){
      query += `, user_type=${user_type}`
    }
    if( master_id !== undefined){
      query += `, master_id=${master_id}`
    }
    if( balance !== undefined){
      query += `, balance=${balance}`
    }
    query += ` where id='${id}'`;
    
    try{
      let {isManager} = await validateManager(req);
      if( !isManager){
        res.json({ 
          code: CODE_ERROR, 
          msg: '无权限', 
          data: null 
        })
        return;
      }
      let data = await querySql(query);
      // console.log('编辑设备===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '更新数据失败', 
          data: null 
        })
      } else {
        await editUserBookIds(id, bookIds);
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '更新数据成功', 
          data: null 
        })
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '更新数据失败', 
        data: err 
      })
    }
  }
}

// 添加用户
async function addUser(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { username,password,nickname,status,gmt_create,bookIds } = req.body;
    if( !gmt_create || gmt_create.length === 0){
      gmt_create = formatTime(new Date());
    }
    if( !password || password.length === 0){
      password = '12345678';
    }
    password = md5(password);
    const query = `insert into sys_user(username,password,nickname,status,gmt_create) values('${username}', '${password}', '${nickname}', ${status}, '${gmt_create}')`;
    try{  
      let {isManager} = await validateManager(req);
      if( !isManager){
        res.json({ 
          code: CODE_ERROR, 
          msg: '无权限', 
          data: null 
        })
        return;
      }
      let find = await findUser(username);
      if( find){
        if( find.delete_flag == 0){
          res.json({ 
            code: CODE_ERROR, 
            msg: '手机号已存在', 
            data: null 
          })
        }else{
          const query = `update sys_user set delete_flag=0,password='${password}',nickname='${nickname}' where id='${find.id}'`;
          let result = await querySql(query)
          // console.log('用户注册===', result);
          if (!result || result.affectedRows === 0) {
            res.json({ 
              code: CODE_ERROR, 
              msg: '注册失败', 
              data: null 
            })
          }else {
            await editUserBookIds(find.id, bookIds);
            res.json({ 
              code: CODE_SUCCESS, 
              msg: '添加数据成功', 
              data: null 
            })
          }
        }
      }else{
        let data = await querySql(query);
        // console.log('添加任务===', data);
        if (!data || data.affectedRows === 0) {
          res.json({ 
            code: CODE_ERROR, 
            msg: '添加数据失败', 
            data: null 
          })
        } else {
          await editUserBookIds(data.insertId, bookIds);
          res.json({ 
            code: CODE_SUCCESS, 
            msg: '添加数据成功', 
            data: null 
          })
        }
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '添加数据失败', 
        data: err 
      })
    }
  }
}

// 删除用户
async function deleteUser(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { id } = req.body;

    const query = `update sys_user set delete_flag=1 where id='${id}'`;
    try{
      let {isManager, self_id} = await validateManager(req);
      if( !isManager && self_id !== id){
        res.json({ 
          code: CODE_ERROR, 
          msg: '无权限', 
          data: null 
        })
        return;
      }
      let data = await querySql(query)
      // console.log('删除用户===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '删除数据失败', 
          data: null 
        })
      } else {
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '删除数据成功', 
          data: null 
        })
      }
    } catch( err) {
      res.json({ 
        code: CODE_ERROR, 
        msg: '删除数据失败', 
        data: err 
      })
    }
  }
}

// 更新用户词汇包
async function editUserBookIds(user_id, bookIds) {
  if(!bookIds){
    return;
  }
  let dataOld = await querySql(`select book_id from sys_user_book where user_id=${user_id}`);
  let deleteIds = [];
  for( let i of dataOld){
    let index = bookIds.indexOf(i.book_id);
    if( index < 0){
      deleteIds.push(i.book_id);
    }else{
      bookIds.splice(index, 1);
    }
  }
  if( deleteIds.length > 0){
    let sql = `delete from sys_user_book where user_id=${user_id} and book_id in (${deleteIds.join(',')})`;
    await querySql(sql);
  }
  if( bookIds.length > 0){
    let sql = `insert into sys_user_book(user_id, book_id) values`;
    for( let i of bookIds){
      sql += `(${user_id}, ${i}),`
    }
    sql = sql.substring(0, sql.length - 1);
    await querySql(sql);
  }
}

// 添加金币
async function addGold(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { id=0, addGoldNum=0 } = req.body;
    let query = `select balance from sys_user where id='${id}'`;
    
    try{
      let data = await querySql(query);
      // console.log('编辑设备===', data);
      if (!data || data.length === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '没有这个用户', 
          data: null 
        })
      } else {
        if( data[0].balance + addGoldNum < 0){
          res.json({ 
            code: CODE_ERROR, 
            msg: '金币不能小于0', 
            data: null 
          })
        }else{
          let sql = `update sys_user set balance=balance+${addGoldNum} where id='${id}'`;
          let result = await querySql(sql);
          if (!result || result.affectedRows === 0) {
            res.json({ 
              code: CODE_ERROR, 
              msg: '更新数据失败', 
              data: err 
            })
          }else{
            res.json({ 
              code: CODE_SUCCESS, 
              msg: '更新数据成功', 
              data: null 
            })
          }
        }
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '更新数据失败', 
        data: err 
      })
    }
  }
}

module.exports = {
  login,
  register,
  resetPwd,
  getUserList,
  editUser,
  addUser,
  deleteUser,
  addGold,
}
